﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



namespace Anuntiomatic.Server
{
    public partial class SysUserPage : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDataGrid();
                BindDropDownData();
            }
        }

        void BindDataGrid()
        {
            string userName = txtSearchName.Text.Trim();
            int? groupId = ddlSearchGroup.SelectedValue == "" ? (int?)null : int.Parse(ddlSearchGroup.SelectedValue);
            bool? disable = ddlSearchDisable.SelectedValue == "" ? (bool?)null : bool.Parse(ddlSearchDisable.SelectedValue);
            grvSysUser.DataSource = SysUser.GetAll(userName, groupId, disable);
            grvSysUser.DataBind(); // bind dữ liệu xuống client.
        }

        private void BindDropDownData()
        {
            var groupList = SysGroup.GetAll();
            BindDropDownListData(ddlSearchGroup, groupList, "GroupID", "GroupName", new ListItem("", ""));
            BindListBoxData(ddlGroup, groupList, "GroupID", "GroupName", new ListItem("", ""));
            BindListBoxData(ddlNewGroup, groupList, "GroupID", "GroupName", new ListItem("", ""));
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
            try
            {
                ControlClass.ResetControlValues(pn_dialog_addnew);
                lbAddNewMsg.Text = "";
                ddlNewGroup.ClearSelection();
                RegisterStartUpScript("OpenDialog('dialog_addnew',400);");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void lbtRefresh_Click(object sender, EventArgs e)
        {
            BindDataGrid();
        }

        protected void grvSysUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName)
                {
                    case "Editing":
                        //passwordRow.Visible = false;
                        hdfObjectId.Value = id.ToString();
                        SysUser obj = DB.SysUsers.FirstOrDefault(p => p.UserID == id);
                        if (obj != null)
                        {
                            hdfObjectId.Value = obj.UserID.ToString();
                            txtUserName.Text = obj.UserName;
                            txtFullName.Text = obj.FullName;
                            txtEmail.Text = obj.Email;
                            txtPhone.Text = obj.Phone;
                            txtAddress.Text = obj.Address;
                            chkDisable.Checked = obj.Disabled;
                            ddlGroup.ClearSelection();
                            foreach (var item in obj.SysUserGroups.Where(p => p.UserID == obj.UserID))
                            {
                                ListItem listItem = ddlGroup.Items.FindByValue(item.GroupID.ToString());
                                if (listItem != null)
                                    listItem.Selected = true;
                            }
                        }
                        lbEditMsg.Text = "";
                        RegisterStartUpScript("OpenDialog('dialog-form',400);");
                        break;
                    case "Deleting":
                        Authorize(Role.Write);
                        var deleteObj = DB.SysUsers.FirstOrDefault(p => p.UserID == id);
                        if (deleteObj != null)
                        {
                            if (deleteObj.IsRootAdmin())
                                throw new Exception("Không được phép xóa tài khoản admin");
                            deleteObj.Deleted = true;
                            DB.SubmitChanges();
                            //Insert change log
                            InsertChangeLog("Xóa người dùng: " + deleteObj.UserName);
                            BindDataGrid();
                        }
                        break;
                    case "ResetPassword":
                        hdfObjectId.Value = id.ToString();
                        txtChangePasswordUser.Text = SysUser.GetName(id);
                        lbMsgResetPassword.Text = "";
                        RegisterStartUpScript("OpenDialog('dialogResetPassword',400);");
                        break;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                int id = 0;
                int.TryParse(hdfObjectId.Value, out id);
                var obj = DB.SysUsers.FirstOrDefault(p => p.UserID == id);
                if (obj != null)
                {
                    obj.Disabled = chkDisable.Checked;
                    obj.FullName = txtFullName.Text.Trim();
                    obj.Email = txtEmail.Text.Trim();
                    obj.Phone = txtPhone.Text.Trim();
                    obj.Address = txtAddress.Text.Trim();

                    if (ValidateInfo(obj))
                    {
                        DB.SysUserGroups.DeleteAllOnSubmit(DB.SysUserGroups.Where(p => p.UserID == obj.UserID));
                        int[] selectedItems = ddlGroup.GetSelectedIndices();
                        for (int i = 0; i < selectedItems.Length; i++)
                        {
                            if (ddlGroup.Items[selectedItems[i]].Value != "")
                            {
                                DB.SysUserGroups.InsertOnSubmit(new SysUserGroup()
                                {
                                    UserID = obj.UserID,
                                    GroupID = int.Parse(ddlGroup.Items[selectedItems[i]].Value)
                                });
                            }
                        }
                        DB.SubmitChanges();
                        InsertChangeLog("Sửa thông tin người dùng: " + obj.UserName);
                        BindDataGrid();
                    }
                    else
                    {
                        RegisterStartUpScript("OpenDialog('dialog-form',400);");
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (ValidateInfo())
                {
                    SysUser obj = new SysUser()
                    {
                        UserName = txtNewUserName.Text.Trim(),
                        Password = txtNewPassWord.Text.ToMD5Hash(),
                        FullName = txtNewFullName.Text,
                        Email = txtNewEmail.Text,
                        Phone = txtNewPhone.Text,
                        Address = txtNewAddress.Text,
                        CreatedDate = DateTime.Now,
                        Disabled = false,
                        Deleted = false
                    };
                    DB.SysUsers.InsertOnSubmit(obj);
                    int[] selectedItems = ddlNewGroup.GetSelectedIndices();
                    for (int i = 0; i < selectedItems.Length; i++)
                    {
                        if (ddlNewGroup.Items[selectedItems[i]].Value != "")
                        {
                            DB.SysUserGroups.InsertOnSubmit(new SysUserGroup()
                            {
                                SysUser = obj,
                                GroupID = int.Parse(ddlNewGroup.Items[selectedItems[i]].Value)
                            });
                        }
                    }
                    DB.SubmitChanges();
                    InsertChangeLog("Thêm mới người dùng: " + obj.UserName);
                    BindDataGrid();
                }
                else
                {
                    RegisterStartUpScript("OpenDialog('dialog_addnew',400);");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindDataGrid();
        }
        
        protected override bool ValidateInfo(object entity)
        {
            SysUser obj = (SysUser)entity;
            string errMsg = string.Empty;
            if (obj.AgencyID == 0)
                errMsg = "Bắt buộc chọn đại lý";
            if (string.IsNullOrWhiteSpace(obj.Email))
                errMsg = "Bắt buộc nhập email!";
            if(string.IsNullOrWhiteSpace(obj.UserName))
                errMsg = "Bắt buộc nhập User name!";
            if (errMsg != string.Empty)
            {
                lbEditMsg.Text = errMsg;
                return false;
            }
            return true;
        }

        protected override bool ValidateInfo()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrWhiteSpace(txtNewPassWord.Text))
                errMsg = "Bắt buộc nhập mật khẩu!";
            if (!txtNewPassWord.Text.Equals(txtReNewPassWord.Text))
                errMsg = "Nhập lại mật khẩu không chính xác!";
            if (string.IsNullOrWhiteSpace(txtNewUserName.Text))
                errMsg = "Bắt buộc nhập User name!";
            if (DB.SysUsers.Any(p => p.UserName == txtNewUserName.Text.Trim()))
                errMsg = "User name đã tồn tại trong hệ thống!";
            if (errMsg != string.Empty)
            {
                lbAddNewMsg.Text = errMsg;
                return false;
            }
            return true;
        }

        protected void btnSaveResetPassword_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                int id = int.Parse(hdfObjectId.Value);
                var obj = DB.SysUsers.FirstOrDefault(p => p.UserID == id);
                string err = string.Empty;
                if (obj != null)
                {
                    if (txtNewRsPassword.Text != txtReNewRsPassword.Text)
                    {
                        err = "Nhập lại mật khẩu không chính xác";
                    }
                    if (string.IsNullOrWhiteSpace(txtNewRsPassword.Text))
                    {
                        err = "Chưa nhập mật khẩu mới";
                    }
                    if (err == "")
                    {
                        obj.Password = txtNewRsPassword.Text.ToMD5Hash();
                        obj.RequiredChangePassword = true;
                        DB.SubmitChanges();
                        InsertChangeLog("Đổi mật khẩu người dùng: " + obj.UserName);
                    }
                    else
                    {
                        lbMsgResetPassword.Text = err;
                        RegisterStartUpScript("OpenDialog('dialogResetPassword',400);");
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }
}